﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;

namespace PlanningGIS.Util.Drawing
{
    /// <summary>
    /// 图片Image与其他数据形式之间的转换
    /// 作者  2015.11.18
    /// </summary>
    public class ImageTransformer
    {
        /// <summary>
        /// Image对象转化为二进制数组
        /// </summary>
        /// <param name="img">Image图片</param>
        /// <returns>二进制数组</returns>
        public static byte[] GetByteFromImage(Image img)
        {
            byte[] bt = null;
            try
            {
                if (img != null)
                {
                    using (MemoryStream mostream = new MemoryStream())
                    {
                        //Bitmap bmp = new Bitmap(img);
                        img.Save(mostream, System.Drawing.Imaging.ImageFormat.Bmp);//将图像以指定的格式存入缓存内存流
                        bt = new byte[mostream.Length];
                        mostream.Position = 0;//设置留的初始位置
                        mostream.Read(bt, 0, Convert.ToInt32(bt.Length));
                        mostream.Close();
                    }
                }
                return bt;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        /// <summary>
        /// 二进制数组转化为Image对象
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static Image GetImageFromByte(byte[] bytes)
        {
            Image image = null;
            try
            {

                if (bytes == null || bytes.Length <= 0) return image;
                MemoryStream ms = new MemoryStream(bytes);
                image = Image.FromStream(ms);
                return image;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        /// <summary>
        /// 指定路径的图片的物理大小
        /// </summary>
        /// <param name="fileName">路径</param>
        /// <returns>图片大小(long)</returns>
        public static long GetImageSizeFromFile(string fileName)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite);
                Bitmap bt = new Bitmap(fs);
                int streamLength = (int)fs.Length;
                byte[] image = new byte[streamLength];
                fs.Read(image, 0, streamLength);
                return (long)(image.Length / 1024);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                fs.Close();
            }
        }
    }
}
